<template>
  <div>
    <div>
      <el-row>
        <el-col :span="20">
          <el-form v-model="search" :inline="true">
            <el-form-item>
              <el-input placeholder="输入搜索关键字" v-model="search.name"
                        clearable/>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="load">查询</el-button>
              <el-button type="info" @click="reset">重置</el-button>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="4" style="text-align: right">
          <el-button size="mini" type="success" @click="addBlog">新增</el-button>
        </el-col>
      </el-row>
    </div>

    <div>
      <el-table
          ref="blogListTable"
          v-loading="tableDataLoading"
          :data="blogList"
          tooltip-effect="dark"
          :header-cell-style="{fontWeight:'normal', color:'#666'}"
      >
        <el-table-column prop="title" label="标题" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-badge v-if="scope.row.topRank > 0" value="top" class="badge-dot"/>
            {{ scope.row.title }}
          </template>
        </el-table-column>
        <el-table-column prop="statu" label="状态" width="90" align="center">
          <template slot-scope="scope">
            <el-badge is-dot :type="getStatus(scope.row.statu).type" class="badge-dot"/>
            {{ getStatus(scope.row.statu).name }}
          </template>
        </el-table-column>
        <el-table-column prop="category" label="分类" width="130">
          <template slot-scope="scope">
            {{ (scope.row.category != null && scope.row.category.id > 0) ? scope.row.category.name : '未分类' }}
          </template>
        </el-table-column>
        <el-table-column label="标签" width="240" show-overflow-tooltip>
          <template slot-scope="scope">
            <div class="tag-group">
              <el-tag v-for="tag in scope.row.tags" :key="tag.id" :type="getRandomTagType()" size="mini">
                {{ tag.name }}
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="commentCount" label="评论量" width="80" align="center">
          <template slot-scope="scope">
            <el-tag effect="dark" size="small" style="border-radius: 50%">{{ scope.row.commentCount }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="visits" label="访问量" width="80" align="center">
          <template slot-scope="scope">
            <el-tag effect="dark" type="warning" size="small" style="border-radius: 50%">{{ scope.row.visits }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="created" label="发布时间" width="160" :formatter="dateFormat" align="center"/>
        <el-table-column label="操作" width="200">
          <template slot-scope="scope">
            <el-button-group>
              <!-- 按钮 1：编辑/还原 -->
              <el-button
                  v-if="scope.row.statu===2"
                  type="primary"
                  size="mini"
                  @click="statusRecycleToPublish(scope.$index)"
              >草稿
              </el-button>
              <router-link
                  v-else
                  class="el-button el-button--primary el-button--mini"
                  :to="{path:'/blog/write', query:{blogId:scope.row.id}}"
              >编辑
              </router-link>
              <!-- 按钮 2：设置 -->
              <el-button type="success" size="mini" @click="openSittingDrawer(scope.$index)">设置</el-button>
              <!-- 按钮 3 ：回收站/删除-->
              <el-popconfirm
                  placement="top-start"
                  confirm-button-text="确定"
                  cancel-button-text="取消"
                  icon="el-icon-info"
                  icon-color="red"
                  :title="scope.row.statu === 2
                  ?`您要永久删除博客【${scope.row.title}】吗？`
                  :`您要将博客【${scope.row.title}】移至回收站吗？`"
                  @confirm="changeStatus(scope.$index)"
              >
                <el-button v-if="scope.row.statu===2" slot="reference" type="danger" size="mini">删除</el-button>
                <el-button v-else slot="reference" type="danger" size="mini">回收站</el-button>
              </el-popconfirm>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5,10,20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>

      <setting ref="drawer" @handleClose="drawerClose" @handleSuccess="this.load"/>
    </div>
  </div>
</template>

<script>
import {updateBlog, getBlogList, deleteBlog} from "@/api/blog/blog";

import setting from "./Setting"

export default {
  name: "BlogList",
  components: {setting},
  data() {
    return {
      search: {},
      //表格加载
      tableDataLoading: false,
      blogList: [],

      currentPage: 1,
      pageSize: 5,
      total: 0,
    }
  },
  created() {
    this.load()
  },
  methods: {
    load() {
      this.tableDataLoading = true
      const params = {
        name: this.search.name,
        currentPage: this.currentPage,
        pageSize: this.pageSize
      }
      getBlogList(params).then(res => {
        this.blogList = res.data.records
        this.currentPage = res.data.current
        this.pageSize = res.data.size
        this.total = res.data.total
        this.tableDataLoading = false
      }).catch(() => {
        this.tableDataLoading = false
      })
    },
    reset() {
      this.search = {}
      this.pageSize = 5;
      this.currentPage = 1
      this.load()
    },
    addBlog() {
      this.$router.replace("/blog/write")
    },
    //获取博客状态
    getStatus(val) {
      const status = {
        0: {
          name: '已发表',
          type: 'success'
        },
        1: {
          name: '草稿箱',
          type: 'info'
        },
        2: {
          name: '回收站',
          type: 'danger'
        }
      }
      const s = status[val]
      return s || {name: '', type: ''}
    },
    getRandomTagType() {
      const tagType = ['', 'info', 'success', 'warning', 'danger']
      return tagType[Math.floor(Math.random() * tagType.length)]
    },
    //将回收站中博客还原至草稿箱
    statusRecycleToPublish(index) {
      const blog = this.blogList[index]
      blog.statu = 1
      updateBlog(blog).then(res => {
        this.$message.success(res.message)
        this.load()
      })
    },
    openSittingDrawer(index) {
      const blog = this.blogList[index]
      this.$refs.drawer.setData(blog)
      this.$refs.drawer.openDrawer()
    },
    //改变当前文章状态
    changeStatus(index) {
      const blog = this.blogList[index]
      const statu = blog.statu
      //2 为 回收站，显示删除按钮
      if (statu === 2) {
        //  在回收站中，删除
        deleteBlog(blog).then(res => {
          this.$message.success(res.message)
          this.load()
        })
      } else {
        //将文章放到回收站中
        blog.statu = 2
        updateBlog(blog).then(res => {
          this.$message.success(res.message)
          this.load()
        })
      }
    },

    handleSizeChange(pageSize) {
      this.pageSize = pageSize
      this.load()
    },
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage
      this.load()
    },
    /*日期处理*/
    dateFormat(row, column) {
      let date = row[column.property];
      if (date === undefined) {
        return ''
      }
      return this.$moment(date).format("YYYY-MM-DD HH:mm:ss");
    },
    //抽屉关闭前的操作
    drawerClose() {
    }
  },
}
</script>

<style scoped>
.badge-dot {
  margin-right: 3px;
  position: relative;
  transform: translateY(25%);
}
</style>
